package com.py.credit.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSONObject;
import com.py.credit.dao.DataEntryDao;
import com.py.credit.dao.ErrorDataDao;
import com.py.credit.entity.Column;
import com.py.credit.entity.ErrorData;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.Table;
import com.py.credit.entity.TableResult;
import com.py.credit.service.ErrorDataService;
import com.py.framework.core.common.Page;
@Service
public class ErrorDataServiceImpl implements ErrorDataService {
	@Autowired
	private ErrorDataDao errorDataDao;

	@Override
	public Integer getcontentId() {
		
		return errorDataDao.getcontentId();
	}

	@Override
	public List<Map<String, Object>> getTableListForPage(Integer tableId, String startTime, String endTime, Page page,
			SysUser userInfo,Integer deptId) {
		
		Table table = errorDataDao.selectByPrimaryKey(tableId);
		if (null != table && StringUtils.isNotBlank(table.getResourceId())) {
			// 获取所有列
			List<Column> columns = errorDataDao.getListByTableId(table.getTableId());
			String tableName = "t_" + table.getResourceId();
			Date day = new Date();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
			if (startTime.equals("")) {
				// 开始时间默认为一个月前
				Calendar c = Calendar.getInstance();
				c.setTime(day);
				c.add(Calendar.MONTH, -1);
				startTime = df.format(c.getTime());
			}
			if (endTime.equals("")) {
				// 结束时间默认为当天
				endTime = df.format(day);
			}
			// 获取异常的表数据
						List<Map<String, Object>> data = null;
						if(userInfo.getRoleName().equals("系统管理员")) {
							data = errorDataDao.getTableListForPage(tableName, startTime, endTime, page,
									deptId==null?null:deptId.longValue());
						}else {
							data = errorDataDao.getTableListForPage(tableName, startTime, endTime, page,
									userInfo.getOfficeId());
						}
			List<Map<String,Object>> newData = new ArrayList<>();
			for (Map<String, Object> m : data) {
				Map<String,Object> map = new LinkedHashMap<String,Object>();
				String jsonValue = "";
				if (null != m) {
					if ("E".equals(m.get("status"))) {
						// 获取异常信息集合
						List<ErrorData> errorDatas = errorDataDao.getErrorDataListForTableId(tableId,
								Integer.parseInt(String.valueOf(m.get("record_id"))));
						if (!CollectionUtils.isEmpty(errorDatas)) {
							Map<String, String> err = new HashMap<String, String>(errorDatas.size());
							Set<String> msg = new HashSet<String>(3);
							String typeMsgReason = "";
							// 表规则字段规则提示处理
							for (ErrorData e : errorDatas) {
								if (null != e) {
									if ("Z".equals(e.getType())) {
										msg.add("字段规则校验失败");
										err.put(e.getColunmEN(), e.getReason());
									} else if ("B".equals(e.getType())) {
										msg.add("表规则校验失败");
										typeMsgReason = e.getReason();
									} else if ("S".equals(e.getType())) {
										msg.add("数据库规则校验失败");
										typeMsgReason = e.getReason();
										jsonValue = e.getColunmValue();
										// 进行数据填充
										
									}
								}
							}
							map.put("typeMsg", StringUtils.join(msg.toArray(), ","));
							map.put("typeMsgReason", typeMsgReason+" 字段规则校验失败:"+err);
							map.put("errorMess", err);
							for (Entry<String, Object> entry : m.entrySet()) {
								if("".equals(entry.getValue()) || null == (entry.getValue()))
								map.put(entry.getKey(), "");
								else
								map.put(entry.getKey(), entry.getValue());
							}
							if (StringUtils.isNotBlank(jsonValue) && !CollectionUtils.isEmpty(columns)) {
								JSONObject jb = JSONObject.parseObject(jsonValue);
								for (Column c : columns) {
									String code = c.getMetricCode();
									map.put(code, jb.getString(code));
								}
							}
						}
					}
				}
				newData.add(map);
			}
			return newData;
		} else {
			return new ArrayList<Map<String, Object>>();
		}			
	}

	@Override
	public void deleteErrorData(Integer tableId, List<String> list, List<String> batchIds) {
		Table table = errorDataDao.selectByPrimaryKey(tableId);
		String tableName = "t_" + table.getResourceId();
		//基础表数据删除
		errorDataDao.deleteErrorData(tableName,list);
		for(int i=0;i<list.size();i++) {
			//错误表数据删除
			errorDataDao.updataErrorData(tableId, Integer.valueOf(list.get(i)), "D");
		}
		for(int j=0;j<batchIds.size();j++) {
			// 异常数据处理时错误减正确加
			errorDataDao.updateTFcount(batchIds.get(j));	
		}
	
		
	}

	@Override
	public TableResult getTableColumns(Integer tableId, Integer contentId, String tipId) {
		
		return errorDataDao.getTableColumns(tableId,contentId,tipId);
	}

}
